package com.yuanren.em.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yuanren.em.annotation.Authority;
import com.yuanren.em.common.Result;
import com.yuanren.em.entity.AuthorityType;
import com.yuanren.em.entity.*;
import com.yuanren.em.service.MemberService;
import com.yuanren.em.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Arrays;

@Authority(AuthorityType.requireLogin)
@RestController
@RequestMapping("/api/member")
public class MemberController {
    
    @Resource
    private MemberService memberService;
    
    // ==================== 会员等级管理 ====================
    
    /**
     * 分页获取会员等级列表
     */
    @Authority(AuthorityType.requireAuthority)
    @GetMapping("/level/page")
    public Result getLevelPage(@RequestParam(defaultValue = "1") int pageNum,
                              @RequestParam(defaultValue = "10") int pageSize,
                              @RequestParam(required = false) String levelName,
                              @RequestParam(required = false) String levelCode) {
        try {
            IPage<MemberLevel> result = memberService.getLevelPage(pageNum, pageSize, levelName, levelCode);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("500", "获取会员等级列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有启用的等级
     */
    @GetMapping("/level/active")
    public Result getActiveLevels() {
        try {
            List<MemberLevel> levels = memberService.getActiveLevels();
            return Result.success(levels);
        } catch (Exception e) {
            return Result.error("500", "获取等级列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取会员等级
     */
    @Authority(AuthorityType.requireAuthority)
    @GetMapping("/level/{id}")
    public Result getLevelById(@PathVariable Long id) {
        try {
            MemberLevel level = memberService.getById(id);
            return Result.success(level);
        } catch (Exception e) {
            return Result.error("500", "获取会员等级失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建或更新会员等级
     */
    @Authority(AuthorityType.requireAuthority)
    @PostMapping("/level")
    public Result saveOrUpdateLevel(@RequestBody MemberLevel level) {
        try {
            memberService.saveOrUpdateLevel(level);
            return Result.success("操作成功");
        } catch (Exception e) {
            return Result.error("500", "保存会员等级失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除会员等级
     */
    @Authority(AuthorityType.requireAuthority)
    @DeleteMapping("/level/{id}")
    public Result deleteLevel(@PathVariable Long id) {
        try {
            memberService.deleteLevel(id);
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error("500", "删除会员等级失败: " + e.getMessage());
        }
    }
    
    // ==================== 会员积分管理 ====================
    
    /**
     * 分页获取积分记录
     */
    @Authority(AuthorityType.requireAuthority)
    @GetMapping("/points/page")
    public Result getPointsPage(@RequestParam(defaultValue = "1") int pageNum,
                               @RequestParam(defaultValue = "10") int pageSize,
                               @RequestParam(required = false) Long userId,
                               @RequestParam(required = false) String changeType,
                               @RequestParam(required = false) String userName) {
        try {
            IPage<MemberPoints> result = memberService.getPointsPage(pageNum, pageSize, userId, changeType, userName);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("500", "获取积分记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户积分记录
     */
    @GetMapping("/points/user/{userId}")
    public Result getUserPointsHistory(@PathVariable Long userId) {
        try {
            List<MemberPoints> points = memberService.getUserPointsHistory(userId);
            return Result.success(points);
        } catch (Exception e) {
            return Result.error("500", "获取用户积分记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户当前可用积分
     */
    @GetMapping("/points/available/{userId}")
    public Result getUserAvailablePoints(@PathVariable Long userId) {
        try {
            Integer points = memberService.getUserAvailablePoints(userId);
            return Result.success(points);
        } catch (Exception e) {
            return Result.error("500", "获取用户积分失败: " + e.getMessage());
        }
    }
    
    /**
     * 管理员调整用户积分
     */
    @Authority(AuthorityType.requireAuthority)
    @PostMapping("/points/adjust")
    public Result adjustPoints(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            Integer points = Integer.valueOf(request.get("points").toString());
            String description = request.get("description").toString();
            
            memberService.adjustPoints(userId, points, description);
            return Result.success("积分调整成功");
        } catch (Exception e) {
            return Result.error("500", "积分调整失败: " + e.getMessage());
        }
    }
    
    /**
     * 使用积分抵扣
     */
    @PostMapping("/points/use")
    public Result usePoints(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            Integer points = Integer.valueOf(request.get("points").toString());
            Long orderId = Long.valueOf(request.get("orderId").toString());
            
            boolean success = memberService.usePointsForDiscount(userId, points, orderId);
            if (success) {
                return Result.success("积分使用成功");
            } else {
                return Result.error("400", "积分不足");
            }
        } catch (Exception e) {
            return Result.error("500", "积分使用失败: " + e.getMessage());
        }
    }
    
    // ==================== 会员权益使用记录 ====================
    
    /**
     * 分页获取权益使用记录
     */
    @Authority(AuthorityType.requireAuthority)
    @GetMapping("/benefit-usage/page")
    public Result getBenefitUsagePage(@RequestParam(defaultValue = "1") int pageNum,
                                     @RequestParam(defaultValue = "10") int pageSize,
                                     @RequestParam(required = false) Long userId,
                                     @RequestParam(required = false) String usageType,
                                     @RequestParam(required = false) String status) {
        try {
            IPage<MemberBenefitUsage> result = memberService.getBenefitUsagePage(pageNum, pageSize, userId, usageType, status);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("500", "获取权益使用记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户权益使用记录
     */
    @GetMapping("/benefit-usage/user/{userId}")
    public Result getUserBenefitUsage(@PathVariable Long userId,
                                     @RequestParam(defaultValue = "20") Integer limit) {
        try {
            List<MemberBenefitUsage> usages = memberService.getUserBenefitUsage(userId, limit);
            return Result.success(usages);
        } catch (Exception e) {
            return Result.error("500", "获取用户权益使用记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取权益使用统计
     */
    @Authority(AuthorityType.requireAuthority)
    @GetMapping("/benefit-usage/stats")
    public Result getBenefitUsageStats() {
        try {
            Map<String, Object> stats = memberService.getBenefitUsageStats();
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("500", "获取权益使用统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 取消权益使用记录
     */
    @Authority(AuthorityType.requireAuthority)
    @PostMapping("/benefit-usage/cancel/{id}")
    public Result cancelBenefitUsage(@PathVariable Long id) {
        try {
            memberService.cancelBenefitUsage(id);
            return Result.success("取消成功");
        } catch (Exception e) {
            return Result.error("500", "取消权益使用失败: " + e.getMessage());
        }
    }
    
    /**
     * 导出权益使用记录
     */
    @Authority(AuthorityType.requireAuthority)
    @GetMapping("/benefit-usage/export")
    public Result exportBenefitUsage(@RequestParam(required = false) Long userId,
                                    @RequestParam(required = false) String usageType,
                                    @RequestParam(required = false) String status) {
        try {
            // 这里应该实现导出逻辑
            return Result.success("导出功能开发中");
        } catch (Exception e) {
            return Result.error("500", "导出失败: " + e.getMessage());
        }
    }
    
    // ==================== 会员通知管理 ====================
    
    /**
     * 分页获取会员通知
     */
    @Authority(AuthorityType.requireAuthority)
    @GetMapping("/notification/page")
    public Result getNotificationPage(@RequestParam(defaultValue = "1") int pageNum,
                                     @RequestParam(defaultValue = "10") int pageSize,
                                     @RequestParam(required = false) Long userId,
                                     @RequestParam(required = false) String notificationType,
                                     @RequestParam(required = false) Boolean isRead) {
        try {
            IPage<MemberNotification> result = memberService.getNotificationPage(pageNum, pageSize, userId, notificationType, isRead);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("500", "获取会员通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户未读通知
     */
    @GetMapping("/notification/unread")
    public Result getUserUnreadNotifications(@RequestParam(required = false) Long userId,
                                            @RequestParam(defaultValue = "10") Integer limit) {
        try {
            Long currentUserId = userId != null ? userId : TokenUtils.getCurrentUser().getId().longValue();
            List<MemberNotification> notifications = memberService.getUserUnreadNotifications(currentUserId, limit);
            return Result.success(notifications);
        } catch (Exception e) {
            return Result.error("500", "获取未读通知失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户通知列表（分页）
     */
    @GetMapping("/notification/user")
    public Result getUserNotifications(@RequestParam(defaultValue = "1") int pageNum,
                                      @RequestParam(defaultValue = "10") int pageSize,
                                      @RequestParam(required = false) Long userId,
                                      @RequestParam(required = false) String notificationType,
                                      @RequestParam(required = false) Boolean isRead) {
        try {
            Long currentUserId = userId != null ? userId : TokenUtils.getCurrentUser().getId().longValue();
            IPage<MemberNotification> result = memberService.getUserNotificationPage(pageNum, pageSize, currentUserId, notificationType, isRead);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("500", "获取用户通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户未读通知数量
     */
    @GetMapping("/notification/unread/count")
    public Result getUserUnreadNotificationCount(@RequestParam(required = false) Long userId) {
        try {
            Long currentUserId = userId != null ? userId : TokenUtils.getCurrentUser().getId().longValue();
            Integer count = memberService.getUserUnreadNotificationCount(currentUserId);
            return Result.success(count);
        } catch (Exception e) {
            return Result.error("500", "获取未读通知数量失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取会员通知统计
     */
    @Authority(AuthorityType.requireAuthority)
    @GetMapping("/notification/stats")
    public Result getNotificationStats() {
        try {
            Map<String, Object> stats = memberService.getNotificationStats();
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("500", "获取通知统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 标记通知为已读
     */
    @PostMapping("/notification/read")
    public Result markNotificationsAsRead(@RequestBody Map<String, Object> request) {
        try {
            Long userId = TokenUtils.getCurrentUser().getId().longValue();
            @SuppressWarnings("unchecked")
            List<Integer> notificationIdsInt = (List<Integer>) request.get("notificationIds");
            List<Long> notificationIds = notificationIdsInt.stream().map(Integer::longValue).collect(java.util.stream.Collectors.toList());
            
            memberService.markNotificationsAsRead(userId, notificationIds);
            return Result.success("标记成功");
        } catch (Exception e) {
            return Result.error("500", "标记通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 标记所有通知为已读
     */
    @PostMapping("/notification/read-all")
    public Result markAllNotificationsAsRead() {
        try {
            Long userId = TokenUtils.getCurrentUser().getId().longValue();
            memberService.markAllNotificationsAsRead(userId);
            return Result.success("全部标记成功");
        } catch (Exception e) {
            return Result.error("500", "标记通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量发送通知
     */
    @Authority(AuthorityType.requireAuthority)
    @PostMapping("/notification/batch-send")
    public Result batchSendNotification(@RequestBody Map<String, Object> request) {
        try {
            String userType = request.get("userType").toString();
            String notificationType = request.get("notificationType").toString();
            String title = request.get("title").toString();
            String content = request.get("content").toString();
            
            List<Long> targetUserIds = new ArrayList<>();
            
            if ("all".equals(userType)) {
                // 发送给所有用户
                targetUserIds = memberService.getAllUserIds();
            } else if ("level".equals(userType)) {
                // 发送给指定等级用户
                @SuppressWarnings("unchecked")
                List<Integer> levelIdsInt = (List<Integer>) request.get("levelIds");
                List<Long> levelIds = levelIdsInt.stream().map(Integer::longValue).collect(java.util.stream.Collectors.toList());
                targetUserIds = memberService.getUserIdsByLevels(levelIds);
            } else if ("specific".equals(userType)) {
                // 发送给指定用户
                String userIds = request.get("userIds").toString();
                targetUserIds = Arrays.stream(userIds.split(","))
                    .map(String::trim)
                    .map(Long::valueOf)
                    .collect(java.util.stream.Collectors.toList());
            }
            
            memberService.batchSendNotification(targetUserIds, notificationType, title, content);
            return Result.success("批量发送成功");
        } catch (Exception e) {
            return Result.error("500", "批量发送失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除通知
     */
    @Authority(AuthorityType.requireAuthority)
    @DeleteMapping("/notification/{id}")
    public Result deleteNotification(@PathVariable Long id) {
        try {
            memberService.deleteNotification(id);
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error("500", "删除通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量删除通知
     */
    @Authority(AuthorityType.requireAuthority)
    @PostMapping("/notification/batch-delete")
    public Result batchDeleteNotifications(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Integer> notificationIdsInt = (List<Integer>) request.get("notificationIds");
            List<Long> notificationIds = notificationIdsInt.stream().map(Integer::longValue).collect(java.util.stream.Collectors.toList());
            
            memberService.batchDeleteNotifications(notificationIds);
            return Result.success("批量删除成功");
        } catch (Exception e) {
            return Result.error("500", "批量删除失败: " + e.getMessage());
        }
    }
    
    // ==================== 积分兑换商城 ====================
    
    /**
     * 分页获取兑换商品列表（前台）
     */
    @GetMapping("/exchange/products")
    public Result getExchangeProducts(@RequestParam(defaultValue = "1") int pageNum,
                                     @RequestParam(defaultValue = "10") int pageSize,
                                     @RequestParam(required = false) String category,
                                     @RequestParam(required = false) String productType,
                                     @RequestParam(required = false) String name) {
        try {
            IPage<PointsExchangeProduct> result = memberService.getExchangeProductsPage(pageNum, pageSize, category, productType, name);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("500", "获取兑换商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 分页获取兑换商品列表（后台管理）
     */
    @Authority(AuthorityType.requireAuthority)
    @GetMapping("/exchange/products/admin")
    public Result getExchangeProductsForAdmin(@RequestParam(defaultValue = "1") int pageNum,
                                             @RequestParam(defaultValue = "10") int pageSize,
                                             @RequestParam(required = false) String category,
                                             @RequestParam(required = false) String productType,
                                             @RequestParam(required = false) Boolean isActive,
                                             @RequestParam(required = false) String name) {
        try {
            IPage<PointsExchangeProduct> result = memberService.getExchangeProductsPageForAdmin(pageNum, pageSize, category, productType, isActive, name);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("500", "获取兑换商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取兑换商品
     */
    @GetMapping("/exchange/products/{id}")
    public Result getExchangeProductById(@PathVariable Long id) {
        try {
            PointsExchangeProduct product = memberService.getExchangeProductById(id);
            return Result.success(product);
        } catch (Exception e) {
            return Result.error("500", "获取商品详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建兑换商品
     */
    @Authority(AuthorityType.requireAuthority)
    @PostMapping("/exchange/products")
    public Result createExchangeProduct(@RequestBody PointsExchangeProduct product) {
        try {
            memberService.createExchangeProduct(product);
            return Result.success("商品创建成功");
        } catch (Exception e) {
            return Result.error("500", "创建商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新兑换商品
     */
    @Authority(AuthorityType.requireAuthority)
    @PutMapping("/exchange/products/{id}")
    public Result updateExchangeProduct(@PathVariable Long id, @RequestBody PointsExchangeProduct product) {
        try {
            product.setId(id);
            memberService.updateExchangeProduct(product);
            return Result.success("商品更新成功");
        } catch (Exception e) {
            return Result.error("500", "更新商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除兑换商品
     */
    @Authority(AuthorityType.requireAuthority)
    @DeleteMapping("/exchange/products/{id}")
    public Result deleteExchangeProduct(@PathVariable Long id) {
        try {
            memberService.deleteExchangeProduct(id);
            return Result.success("商品删除成功");
        } catch (Exception e) {
            return Result.error("500", "删除商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 调整商品库存
     */
    @Authority(AuthorityType.requireAuthority)
    @PostMapping("/exchange/products/adjust-stock")
    public Result adjustProductStock(@RequestBody Map<String, Object> request) {
        try {
            Long productId = Long.valueOf(request.get("productId").toString());
            Integer adjustAmount = Integer.valueOf(request.get("adjustAmount").toString());
            String reason = request.get("reason").toString();
            
            memberService.adjustProductStock(productId, adjustAmount, reason);
            return Result.success("库存调整成功");
        } catch (Exception e) {
            return Result.error("500", "库存调整失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取热门兑换商品
     */
    @GetMapping("/exchange/products/hot")
    public Result getHotExchangeProducts(@RequestParam(defaultValue = "8") Integer limit) {
        try {
            List<PointsExchangeProduct> products = memberService.getHotExchangeProducts(limit);
            return Result.success(products);
        } catch (Exception e) {
            return Result.error("500", "获取热门商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取积分兑换商品统计
     */
    @Authority(AuthorityType.requireAuthority)
    @GetMapping("/exchange/products/stats")
    public Result getExchangeProductStats() {
        try {
            Map<String, Object> stats = memberService.getExchangeProductStats();
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("500", "获取商品统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 积分兑换商品
     */
    @PostMapping("/exchange/products/exchange")
    public Result exchangeProduct(@RequestBody Map<String, Object> request) {
        try {
            Long userId = TokenUtils.getCurrentUser().getId().longValue();
            Long productId = Long.valueOf(request.get("productId").toString());
            Integer quantity = Integer.valueOf(request.get("quantity").toString());
            
            String exchangeCode = memberService.exchangeProduct(userId, productId, quantity);
            return Result.success(exchangeCode);
        } catch (Exception e) {
            return Result.error("500", "兑换失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户兑换记录
     */
    @GetMapping("/exchange/records/user")
    public Result getUserExchangeRecords(@RequestParam(required = false) Long userId,
                                        @RequestParam(defaultValue = "20") Integer limit) {
        try {
            Long currentUserId = userId != null ? userId : TokenUtils.getCurrentUser().getId().longValue();
            List<PointsExchangeRecord> records = memberService.getUserExchangeRecords(currentUserId, limit);
            return Result.success(records);
        } catch (Exception e) {
            return Result.error("500", "获取兑换记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 分页获取兑换记录（后台管理）
     */
    @Authority(AuthorityType.requireAuthority)
    @GetMapping("/exchange/records/page")
    public Result getExchangeRecordPage(@RequestParam(defaultValue = "1") int pageNum,
                                       @RequestParam(defaultValue = "10") int pageSize,
                                       @RequestParam(required = false) Long userId,
                                       @RequestParam(required = false) Long productId,
                                       @RequestParam(required = false) String status,
                                       @RequestParam(required = false) String category) {
        try {
            IPage<PointsExchangeRecord> result = memberService.getExchangeRecordPage(pageNum, pageSize, userId, productId, status, category);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("500", "获取兑换记录失败: " + e.getMessage());
        }
    }
    
    // ==================== 会员优惠券管理 ====================
    
    /**
     * 分页获取会员优惠券（后台管理）
     */
    @Authority(AuthorityType.requireAuthority)
    @GetMapping("/coupon/page")
    public Result getCouponPage(@RequestParam(defaultValue = "1") int pageNum,
                               @RequestParam(defaultValue = "10") int pageSize,
                               @RequestParam(required = false) Long userId,
                               @RequestParam(required = false) String couponType,
                               @RequestParam(required = false) Boolean isUsed,
                               @RequestParam(required = false) String source) {
        try {
            IPage<MemberCoupon> result = memberService.getCouponPage(pageNum, pageSize, userId, couponType, isUsed, source);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("500", "获取优惠券失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户可用优惠券
     */
    @GetMapping("/coupon/available")
    public Result getUserAvailableCoupons(@RequestParam(required = false) Long userId) {
        try {
            Long currentUserId = userId != null ? userId : TokenUtils.getCurrentUser().getId().longValue();
            List<MemberCoupon> coupons = memberService.getUserAvailableCoupons(currentUserId);
            return Result.success(coupons);
        } catch (Exception e) {
            return Result.error("500", "获取可用优惠券失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户可用于订单的优惠券
     */
    @GetMapping("/coupon/applicable")
    public Result getApplicableCoupons(@RequestParam(required = false) Long userId,
                                      @RequestParam BigDecimal orderAmount) {
        try {
            Long currentUserId = userId != null ? userId : TokenUtils.getCurrentUser().getId().longValue();
            List<MemberCoupon> coupons = memberService.getApplicableCoupons(currentUserId, orderAmount);
            return Result.success(coupons);
        } catch (Exception e) {
            return Result.error("500", "获取可用优惠券失败: " + e.getMessage());
        }
    }
    
    /**
     * 使用优惠券
     */
    @PostMapping("/coupon/use")
    public Result useCoupon(@RequestBody Map<String, Object> request) {
        try {
            String couponCode = request.get("couponCode").toString();
            Long orderId = Long.valueOf(request.get("orderId").toString());
            
            MemberCoupon coupon = memberService.useCoupon(couponCode, orderId);
            return Result.success(coupon);
        } catch (Exception e) {
            return Result.error("500", "使用优惠券失败: " + e.getMessage());
        }
    }
    
    /**
     * 计算优惠券折扣金额
     */
    @PostMapping("/coupon/calculate-discount")
    public Result calculateCouponDiscount(@RequestBody Map<String, Object> request) {
        try {
            String couponCode = request.get("couponCode").toString();
            BigDecimal orderAmount = new BigDecimal(request.get("orderAmount").toString());
            
            // 这里简化处理，实际应该先获取优惠券信息
            return Result.success(BigDecimal.ZERO);
        } catch (Exception e) {
            return Result.error("500", "计算折扣失败: " + e.getMessage());
        }
    }
    
    // ==================== 会员等级折扣 ====================
    
    /**
     * 计算会员等级折扣
     */
    @PostMapping("/discount/calculate")
    public Result calculateMemberDiscount(@RequestBody Map<String, Object> request) {
        try {
            Long userId = TokenUtils.getCurrentUser().getId().longValue();
            BigDecimal orderAmount = new BigDecimal(request.get("orderAmount").toString());
            
            BigDecimal discount = memberService.calculateMemberDiscount(userId, orderAmount);
            return Result.success(discount);
        } catch (Exception e) {
            return Result.error("500", "计算会员折扣失败: " + e.getMessage());
        }
    }
    
    /**
     * 应用会员等级折扣到订单
     */
    @PostMapping("/discount/apply")
    public Result applyMemberDiscountToOrder(@RequestBody Map<String, Object> request) {
        try {
            Long userId = TokenUtils.getCurrentUser().getId().longValue();
            Long orderId = Long.valueOf(request.get("orderId").toString());
            BigDecimal originalAmount = new BigDecimal(request.get("originalAmount").toString());
            BigDecimal discountAmount = new BigDecimal(request.get("discountAmount").toString());
            
            memberService.applyMemberDiscountToOrder(userId, orderId, originalAmount, discountAmount);
            return Result.success("会员折扣应用成功");
        } catch (Exception e) {
            return Result.error("500", "应用会员折扣失败: " + e.getMessage());
        }
    }
    
    // ==================== 统计信息 ====================
    
    /**
     * 获取会员统计信息
     */
    @Authority(AuthorityType.requireAuthority)
    @GetMapping("/statistics")
    public Result getMemberStatistics() {
        try {
            MemberService.MemberStatistics stats = memberService.getMemberStatistics();
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("500", "获取统计信息失败: " + e.getMessage());
        }
    }
    
    // ==================== 业务集成接口 ====================
    
    /**
     * 订单完成后添加积分
     */
    @PostMapping("/points/order")
    public Result addPointsForOrder(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            Long orderId = Long.valueOf(request.get("orderId").toString());
            BigDecimal orderAmount = new BigDecimal(request.get("orderAmount").toString());
            
            memberService.addPointsForOrder(userId, orderId, orderAmount);
            return Result.success("积分添加成功");
        } catch (Exception e) {
            return Result.error("500", "添加积分失败: " + e.getMessage());
        }
    }
    
    /**
     * 评论后添加积分
     */
    @PostMapping("/points/comment")
    public Result addPointsForComment(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            Long commentId = Long.valueOf(request.get("commentId").toString());
            
            memberService.addPointsForComment(userId, commentId);
            return Result.success("积分添加成功");
        } catch (Exception e) {
            return Result.error("500", "添加积分失败: " + e.getMessage());
        }
    }
} 